package com.duan.nowcoder.community.service;

import com.duan.nowcoder.community.entity.Comment;
import com.duan.nowcoder.community.mapper.CommentMapper;
import com.duan.nowcoder.community.util.CommunityConstant;
import com.duan.nowcoder.community.util.SensitiveWordsFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService, CommunityConstant {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private SensitiveWordsFilter sensitiveWordsFilter;
    @Autowired
    private DiscussPostService discussPostService;

    @Override
    public List<Comment> findCommentEntity(int commentType, int commentId, int offset, int limit) {
        return commentMapper.selectCommentByEntity(commentType, commentId, offset, limit);
    }

    @Override
    public int findCommentCount(int commentType, int commentId) {
        return commentMapper.selectCountByEntity(commentType, commentId);
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment) {
        if (comment == null) throw new IllegalArgumentException("参数不能为空！");
        //添加评论
        //处理评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveWordsFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);
        //更新评论数量

        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            discussPostService.updatePostCommentCount(comment.getEntityId(), commentMapper.selectCountByEntity(ENTITY_TYPE_POST, comment.getEntityId()));
        }
        return rows;
    }

    @Override
    public Comment findCommentById(int id) {
        return commentMapper.selectCommentById(id);
    }

    @Override
    public int updateCommentStatus(int entityId, int status) {
        return commentMapper.updateCommentStatus(entityId, status);
    }
}
